<template>
  <div>
    <!-- 面包屑组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 需要用native属性 -->
      <el-breadcrumb-item :to="{ path: '/home' }" @click.native="returnHome"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 树形table 关闭复选框 关闭展开 开启索引-->
      <tree-table
        class="tree-table"
        :data="catesList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-index="true"
        index-text="#"
        border
      >
        <!-- 具名插槽 插槽名叫isUseful 是否有效 -->
        <template v-slot:isUseful="{ row }">
          <i
            class="el-icon-circle-check"
            v-show="!row.cat_deleted"
            style="color: lightgreen"
          ></i>
          <i
            class="el-icon-circle-close"
            v-show="row.cat_deleted"
            style="color: red"
          ></i>
        </template>
        <!-- 排序模板 -->
        <template v-slot:order="{ row }">
          <el-tag size="mini" v-show="row.cat_level == 0">一级</el-tag>
          <el-tag size="mini" type="success" v-show="row.cat_level == 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-show="row.cat_level == 2"
            >三级</el-tag
          >
        </template>
        <!-- 操作模板  -->
        <template v-slot:opts="{ row }">
          <!-- 修改按钮 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(row)"
            >编辑</el-button
          >
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCateById(row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 每次更换也要重新获取数据 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类会话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateRuleForm"
        :rules="addCateRules"
        ref="cateForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateRuleForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- 级联选择器，多级目录分类一目了然 options指定数据对象 -->
          <el-cascader
            v-model="pSelectKeys"
            :options="pCatesList"
            :props="parentProps"
            @change="handlePChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑会话框 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editRuleForm"
        :rules="editRules"
        ref="editRuleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="编辑名称" prop="cat_name">
          <el-input v-model="editRuleForm.cat_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Cate',
  data () {
    return {
      catesList: [],
      total: 0,
      queryInfo: { type: 3, pagenum: 1, pagesize: 5 },
      // 用于指定标题项table
      columns: [{
        label: '分类名称',
        prop: 'cat_name'
      }, {
        label: '是否有效',
        // 指定当前列为自定义模板列，使用作用域插槽
        type: 'template',
        template: 'isUseful'
      }, {
        label: '排序',
        // 指定当前列为自定义模板列，使用作用域插槽
        type: 'template',
        template: 'order'
      }, {
        label: '操作',
        // 指定当前列为自定义模板列，使用作用域插槽
        type: 'template',
        template: 'opts'
      }],
      // 控制添加分类会话
      addCateDialogVisible: false,
      // 校验规则及数据对象
      addCateRuleForm: {
        cat_name: '',
        // 父级分类的Id ，也为等级
        cat_level: 0,
        cat_pid: 0
      },
      addCateRules: {
        cat_name: [{
          required: true, message: '分类名称不能为空！', trigger: 'blur'
        }]
      },
      // 父级分类列表
      pCatesList: [],
      // 级联选择器选中数据
      pSelectKeys: [],
      // 配置对象
      parentProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        checkStrictly: true
      },
      // 编辑会话框
      editDialogVisible: false,
      editRuleForm: {},
      editRules: {
        cat_name: [{
          required: true, message: '分类名称不能为空！', trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    // 依然是点击首页的优化
    returnHome () {
      this.$bus.$emit('changePath')
    },
    // 创建时候获取分类信息列表
    async getCatesList () {
      const { data: res } = await this.$https.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status === 200) {
        // 总数据分类
        this.catesList = res.data.result
        // 总数居条数
        this.total = res.data.total
      } else this.$message.error('信息获取失败！')
    },
    // 处理页码变化
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCatesList()
    },
    // 处理当前页码变化
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCatesList()
    },
    showAddCateDialog () {
      // 先获取父级分类
      this.getParentList()
      this.addCateDialogVisible = true
    },
    // 关闭会话重置里面的内容
    addCateDialogClosed () {
      this.$refs.cateForm.resetFields()
      this.addCateRuleForm.cat_level = 0
      this.addCateRuleForm.cat_pid = 0
      // 刚刚选择的时候便赋值，需要清空
      this.pSelectKeys = []
    },
    // 获取父级分类
    async getParentList () {
      const { data: res } = await this.$https.get('categories', { params: { type: 2 } })
      if (res.meta.status === 200) {
        this.pCatesList = res.data
      } else this.$message.error('获取父级分类失败！')
    },
    // 选择变化时触发
    handlePChange () {
      // 大于0说明有选择
      if (this.pSelectKeys.length > 0) {
        // 等级就是长度 都是从0开始
        this.addCateRuleForm.cat_level = this.pSelectKeys.length
        // 父级就是最后一项
        this.addCateRuleForm.cat_pid = this.pSelectKeys[this.pSelectKeys.length - 1]
      } else {
        this.addCateRuleForm.cat_level = 0
        this.addCateRuleForm.cat_pid = 0
      }
    },
    // 确认提交
    addCate () {
      this.$refs.cateForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$https.post('categories', this.addCateRuleForm)
          if (res.meta.status === 201) {
            this.$message.success('添加分类成功！')
            this.getCatesList()
            this.addCateDialogVisible = false
          } else this.$message.error('添加分类失败！')
        }
      })
    },
    // 具名插槽传递过来当前行的信息
    showEditDialog (cate) {
      this.editRuleForm = cate
      console.log(cate)
      this.editDialogVisible = true
    },
    editDialog () {
      this.$refs.editRuleFormRef.validate(async valid => {
        // 根据后端文件设置
        if (valid) {
          const { data: res } = await this.$https.put('categories/' + this.editRuleForm.cat_id, {
            cat_name: this.editRuleForm.cat_name
          })
          if (res.meta.status === 200) {
            this.$message.success('修改分类成功！')
            this.getCatesList()
            this.editDialogVisible = false
          } else this.$message.error('添加分类失败！')
          console.log(res)
        }
      })
    },
    // 删除
    async deleteCateById (id) {
      // 返回的是一个promise对象 确定返回confirm 否则返回cancel字符串
      const result = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      // 发送删除请求 并刷新列表
      if (result === 'confirm') {
        const { data: res } = await this.$https.delete('categories/' + id)
        if (res.meta.status === 200) {
          this.$message.success('删除成功！')
          this.getCatesList()
        } else this.$message.error('删除失败！')
        console.log(res)
      }
    }
  },
  created () {
    this.getCatesList()
  }
}
</script>

<style scoped>
.tree-table {
  margin-top: 15px;
}
</style>
